package com.zyk.scaffold.tcp.connector;

import com.zyk.scaffold.tcp.proto3.MessageBuf;
import com.zyk.scaffold.tcp.session.Session;
import com.zyk.scaffold.tcp.wrappers.MessageWrapper;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TcpConnectionManager {
    protected Map<String, Connection> connections = new ConcurrentHashMap<String, Connection>();

    public Connection created(ChannelHandlerContext cxt, Session session) {
        Connection connection = TcpConnection.created(cxt, session);
        connections.put(session.getId(), connection);
        return connection;
    }

    public void send(MessageWrapper wrapper) {
        MessageBuf.JMTransfer message = wrapper.toMessageBuf();
        String sessionId = wrapper.getToken();
        send(sessionId, message);
    }

    public void send(String sessionId, MessageBuf.JMTransfer message) {
        Connection connection = connections.get(sessionId);
        connection.send(sessionId, message);
    }

    public void close(String sessionId) {
        if (connections.containsKey(sessionId)) {
            connections.get(sessionId).close();
        }
    }
}
